package org.btallarm.model;

import org.btallarm.json.DataConverter;
import org.btallarm.json.JSONMappingInfo;
import org.btallarm.json.JSONMappingType;
import org.btallarm.json.NotAnnotationDeclaredException;
import org.json.JSONException;
import org.json.JSONObject;

public class Envelop<T> {
 
	public final static int MESSAGE_COMMAND=0;
	public final static int MESSAGE_STATE=1;
	public final static int MESSAGE_THRESHOLD=2;
	public final static int MESSAGE_NOTE=3;
	
	
	private int id;
	
	private T object;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public T getObject() {
		return object;
	}

	public void setObject(T object) {
		this.object = object;
	}
	
	public JSONObject toJSONObject(){
		JSONObject obj= new JSONObject();
		JSONObject subobj= new JSONObject();
		try {
			obj.put("id", this.id);
			DataConverter.toJSONObject(this.object , subobj);
			obj.putOpt("body", subobj);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotAnnotationDeclaredException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
		
	}
	public void fromJSONObject(JSONObject obj){
	
		try {
			this.id=obj.getInt("id");
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			switch( obj.getInt("id") ) {
			case MESSAGE_NOTE:
				this.object = (T) new Note(); 
				break;
			case MESSAGE_COMMAND:
				this.object = (T) new Command(); 
				break;
			case MESSAGE_STATE:
				this.object = (T) new State(); 
				break;
			case MESSAGE_THRESHOLD:
				this.object = (T) new Threshold(); 
				break;
			default:
				break;
					
			}
			DataConverter.fromJSONObject(this.object, obj.getJSONObject("body"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotAnnotationDeclaredException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
